import { defineStore } from "pinia";
import type { reqCategoryType } from "@/api/attr";
import {
    requestCategory1,
    requestCategory2, 
    requestCategory3
} from "@/api/attr";
import { ElMessage } from "element-plus";

// state的类型限制
interface storeType {
    categoryList1:reqCategoryType;
    categoryList2:reqCategoryType;
    categoryList3:reqCategoryType;
    category1Id:number |null;
    category2Id:number |null;
    category3Id:number |null;
}
const useAttrStore = defineStore("attr", {
    // state数据(categoryId在没有值的时候默认设置0，但是后来发现在select中使用的时候，必须要写null,所以我们要改为null)
    state: (): storeType =>{
        return {
            categoryList1:[],
            categoryList2:[],
            categoryList3:[],
            category1Id:null,
            category2Id:null,
            category3Id:null,
        };
    },
    getters :{},
    actions: {
        // 请求一级分类数据
        async getCategory1 () {
            try{
          //发送请求
          const result  = await requestCategory1();
        // 把一级分类的值赋值给state
        this.categoryList1 = result; 
        } catch (e) {
            ElMessage.error("请求一级分类失败");
        }
        },
          //请求二级分类数据
    async getCategory2() {
        try {
          //发送请求
          const result = await requestCategory2(this.category1Id as number);
          //把一级分类的值赋值给state
          this.categoryList2 = result;
        } catch (e) {
          ElMessage.error("请求二级分类失败");
        }
      },
      //请求三级分类数据
      async getCategory3(){
        try{
          // 发送请求
          const result = await requestCategory3(this.category3Id as number);
          // 把二级分类的值赋值给state
          this.categoryList3 = result;
        } catch (e) {
          ElMessage.error("请求三级分类失败");
        }
      }

    }
    });
    
    export default useAttrStore;